﻿using Kernelx.Extensions;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;



namespace Kernelx.Contexts.Repositories
{
    using Core;
    internal class ModelTrack<TModel> : IModelTrack<TModel>
        where TModel : class
    {
        public TModel Model { get; set; }

        public IEnumerable<Alter> AlterProps => _alterProps.Value;

        private readonly Lazy<IEnumerable<Alter>> _alterProps;
        public ModelTrack(EntityEntry<TModel> entityEntry)
        {
            Model = entityEntry.Entity;
            _alterProps = new Lazy<IEnumerable<Alter>>(() => createAlterProps(entityEntry));

            static IEnumerable<Alter> createAlterProps(EntityEntry<TModel> etyEntry)
            {
                var oValues = etyEntry.OriginalValues;
                var nValues = etyEntry.CurrentValues;
                foreach (var p in nValues.Properties)
                {
                    var nValue = nValues[p];
                    var oValue = oValues[p];
                    if (!nValue.IsEquals(oValue))
                        yield return new Alter(p.Name, oValue, nValue);
                }
            }

        }

    }
}
